# -*- coding: utf-8 */
import logging
import pika
from urllib.parse import urlparse
from scrapy.utils.project import get_project_settings

logger = logging.getLogger(__name__)

# 默认的RabbitMQ连接参数
DEFAULT_CONNECTION_PARAMETERS = {
    'host': 'localhost',
    'port': 5672,
    'virtual_host': '/',
    'credentials': {
        'username': 'root',
        'password': 'root'
    },
    'heartbeat': 0,
    'blocked_connection_timeout': 300
}

def from_settings():
    """从settings中获取RabbitMQ连接"""
    settings = get_project_settings()
    params = settings.get('RABBITMQ_CONNECTION_PARAMETERS', {})
    
    # 合并默认参数和用户设置
    connection_params = DEFAULT_CONNECTION_PARAMETERS.copy()
    connection_params.update(params)
    
    # 创建认证凭据
    credentials = pika.PlainCredentials(
        username=connection_params['credentials']['username'],
        password=connection_params['credentials']['password']
    )
    
    # 创建连接参数
    parameters = pika.ConnectionParameters(
        host=connection_params['host'],
        port=connection_params['port'],
        virtual_host=connection_params['virtual_host'],
        credentials=credentials,
        heartbeat=connection_params['heartbeat'],
        blocked_connection_timeout=connection_params['blocked_connection_timeout']
    )
    
    return parameters

def get_queue_name(spider_name):
    """获取队列名称"""
    settings = get_project_settings()
    queue_name = settings.get('RABBITMQ_QUEUE_NAME', None)
    if queue_name is None:
        queue_name = f"scrapy_{spider_name}_queue"
    return queue_name

def connect_rabbitmq(spider_name):
    """连接到RabbitMQ并返回连接和通道"""
    try:
        # 创建连接参数
        parameters = pika.ConnectionParameters(
            host='localhost',
            port=5672,
            credentials=pika.PlainCredentials('root', 'root'),
            heartbeat=600,
            blocked_connection_timeout=300
        )
        
        # 建立连接
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        
        # 声明队列
        queue_name = f'{spider_name}:requests'
        channel.queue_declare(
            queue=queue_name,
            durable=True,  # 持久化队列
            arguments={
                'x-max-priority': 10
            }
        )
        
        logger.info(f"Connected to RabbitMQ, queue: {queue_name}")
        return connection, channel
        
    except Exception as e:
        logger.error(f"Error connecting to RabbitMQ: {e}")
        raise